<template>
  <div class="house-management-container">
    <el-card>
      <div class="management-header">
        <div class="management-title">
          <h2>一级审核管理</h2>
        </div>
      </div>

          <!-- 搜索区域 -->
          <div class="house-search">
            <div class="search-row">
              <el-input
                v-model="searchForm.title"
                placeholder="请输入房源标题"
                style="width: 200px; margin-right: 12px"
                clearable
              />
              <el-select
                v-model="searchForm.countyId"
                placeholder="选择区域"
                style="width: 150px; margin-right: 12px"
                clearable
              >
                <el-option
                  v-for="county in countyList"
                  :key="county.id"
                  :label="county.name"
                  :value="county.id"
                />
              </el-select>
              <el-select
                v-model="searchForm.rentalType"
                placeholder="出租类型"
                style="width: 120px; margin-right: 12px"
                clearable
              >
                <el-option label="整租" :value="1" />
                <el-option label="分租" :value="2" />
              </el-select>
              <div class="rent-range-container">
                <span class="range-label">租金范围：</span>
                <el-input-number
                  v-model="searchForm.rentMin"
                  placeholder="最低租金"
                  :min="0"
                  :max="99999"
                  style="width: 120px; margin-right: 8px"
                  controls-position="right"
                />
                <span class="range-separator">-</span>
                <el-input-number
                  v-model="searchForm.rentMax"
                  placeholder="最高租金"
                  :min="0"
                  :max="99999"
                  style="width: 120px; margin-right: 12px"
                  controls-position="right"
                />
              </div>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </div>
          
          <!-- 房源卡片列表 -->
          <div class="house-cards-container" style="margin-top: 16px;">
            <div v-if="loading" class="loading-state">
              <el-skeleton :rows="3" animated />
            </div>

            <div v-else-if="houseList.length > 0" class="house-cards">
              <div
                v-for="house in houseList"
                :key="house.id"
                class="house-card"
              >
                  <!-- 左侧图片 -->
                  <div class="house-image">
                    <img
                      :src="getFirstImage(house.imageUrls || '') || getDefaultImage()"
                      :alt="house.title"
                      class="house-img"
                      @error="handleImageError"
                    />
                    <div class="house-status">
                      <span class="status-tag" :class="getStatusClass(house.state)">
                        {{ getStatusText(house.state) }}
                      </span>
                    </div>
                    <div class="rental-type-tag">
                      <span class="rental-tag" :class="house.rentalType === 1 ? 'whole-rent' : 'shared-rent'">
                        {{ house.rentalType === 1 ? '整租' : '分租' }}
                      </span>
                    </div>
                  </div>

                  <!-- 中间信息 -->
                  <div class="house-info">
                    <div class="house-card-header">
                      <h3 class="house-title">{{ house.name || house.title || '房源' + house.id }}</h3>
                      <div class="house-right">
                        <div class="house-price">
                          <span class="price-amount">{{ formatMoney(house.rent || house.price || 0) }}</span>
                          <span class="price-unit">元/月</span>
                        </div>
                      </div>
                    </div>

                    <div class="house-details">
                      <div class="detail-item">
                        <span class="detail-label">房源编号：</span>
                        <span class="detail-value">{{ house.houseCode || '暂无' }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="detail-label">房屋面积：</span>
                        <span class="detail-value">{{ house.area || '暂无' }}㎡</span>
                      </div>
                      <div class="detail-item">
                        <span class="detail-label">户型配置：</span>
                        <span class="detail-value">{{ house.typeNum || '暂无' }}室{{ house.type || '暂无' }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="detail-label">详细地址：</span>
                        <span class="detail-value">{{ house.address || '暂无' }}</span>
                      </div>
                      <div class="detail-item" v-if="house.listTime">
                        <span class="detail-label">挂牌时间：</span>
                        <span class="detail-value">{{ formatDate(house.listTime) }}</span>
                      </div>
                    </div>

                    <div class="house-actions">
                      <el-button type="primary" @click="handleViewDetails(house)">
                        详情
                      </el-button>
                      <el-button type="success" @click="handleApprove(house)">
                        通过审核
                      </el-button>
                      <el-button type="danger" @click="handleReject(house)">
                        拒绝审核
                      </el-button>
                    </div>
                  </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="empty-state">
              <el-empty description="暂无待审核房源数据" />
            </div>
          </div>
          
          <!-- 分页 -->
          <div class="table-pagination">
            <el-pagination
              background
              layout="total, prev, pager, next"
              :total="total"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>

    <!-- 房源详情侧滑面板 -->
    <el-drawer
      v-model="showHouseDetailDrawer"
      title="房源详情"
      direction="rtl"
      size="500px"
      :before-close="handleDrawerClose"
    >
      <div v-if="currentHouse" class="house-detail-content">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="detail-label">房源标题：</span>
              <span class="detail-value">{{ currentHouse.title }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">户号：</span>
              <span class="detail-value">{{ currentHouse.num }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">租金：</span>
              <span class="detail-value">{{ formatMoney(currentHouse.rent) }}元/月</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">面积：</span>
              <span class="detail-value">{{ currentHouse.area }}㎡</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">户型：</span>
              <span class="detail-value">{{ currentHouse.typeNum }}室{{ currentHouse.type }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">状态：</span>
              <span class="detail-value">{{ getStatusText(currentHouse.state) }}</span>
            </div>
          </div>
        </div>
        
        <div class="detail-section" v-if="currentHouse.description">
          <h4>房源描述</h4>
          <p class="description-text">{{ currentHouse.description }}</p>
        </div>
        
        <div class="detail-section" v-if="currentHouse.imageUrls">
          <h4>房源图片</h4>
          <div class="image-gallery">
            <img 
              v-for="(image, index) in getImageList(currentHouse.imageUrls)"
              :key="index"
              :src="image"
              :alt="`房源图片${index + 1}`"
              class="detail-image"
              @error="handleImageError"
            />
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import baseService from '@/service/baseService'

// 响应式数据
const loading = ref(false)
const houseList = ref<any[]>([])
const countyList = ref<any[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = 10

// 搜索表单 - 默认状态为1（一级审核中）
const searchForm = reactive({
  title: '',
  countyId: null,
  rentalType: null,
  state: 1, // 固定为一级审核状态
  rentMin: null,
  rentMax: null
})

// 房源详情侧滑面板
const showHouseDetailDrawer = ref(false)
const currentHouse = ref<any>(null)

// 工具函数
const formatMoney = (amount: number) => {
  return new Intl.NumberFormat('zh-CN').format(amount || 0)
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

const getFirstImage = (imageUrls: string) => {
  if (!imageUrls) return ''
  const urls = imageUrls.split(',').filter(url => url.trim())
  return urls.length > 0 ? urls[0].trim() : ''
}

const getImageList = (imageUrls: string) => {
  if (!imageUrls) return []
  return imageUrls.split(',').filter(url => url.trim()).map(url => url.trim())
}

const getDefaultImage = () => {
  return ''
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.warn('图片加载失败:', img.src)
  img.src = getDefaultImage()
  img.onerror = null
}

const getStatusText = (state: number) => {
  const statusMap: { [key: number]: string } = {
    0: '未审核',
    1: '一级审核中',
    2: '二级审核中', 
    3: '三级审核中',
    4: '已上架',
    5: '已出租',
    6: '已下架',
    7: '审核失败'
  }
  return statusMap[state] || '未知状态'
}

const getStatusClass = (state: number) => {
  const classMap: { [key: number]: string } = {
    0: 'status-pending',
    1: 'status-reviewing',
    2: 'status-reviewing',
    3: 'status-reviewing', 
    4: 'status-online',
    5: 'status-rented',
    6: 'status-offline',
    7: 'status-failed'
  }
  return classMap[state] || 'status-pending'
}

// API调用函数
const getHouseList = async () => {
  loading.value = true
  try {
    const queryParams = {
      page: currentPage.value,
      limit: pageSize,
      title: searchForm.title || undefined,
      state: searchForm.state, // 固定为1
      rentalType: searchForm.rentalType || undefined,
      rentMin: searchForm.rentMin || undefined,
      rentMax: searchForm.rentMax || undefined,
      region: searchForm.countyId || undefined
    }
    
    const filteredParams = Object.fromEntries(
      Object.entries(queryParams).filter(([_, value]) => value !== undefined)
    )

    console.log('一级审核查询参数:', filteredParams)

    const response = await baseService.get('/rental/areaplothouse/page/admin', filteredParams)

    if (response.code === 0) {
      houseList.value = response.data.list || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取房源列表失败')
    }
  } catch (error) {
    console.error('获取房源列表失败:', error)
    ElMessage.error('获取房源列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

const getCountyList = async () => {
  try {
    const response = await baseService.get('/rental/areacounty/getAllCounty')
    if (response.code === 0) {
      countyList.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取区域列表失败')
    }
  } catch (error) {
    console.error('获取区域列表失败:', error)
    ElMessage.error('获取区域列表失败，请检查网络连接')
  }
}

// 事件处理函数
const handleSearch = () => {
  currentPage.value = 1
  getHouseList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    countyId: null,
    rentalType: null,
    state: 1, // 保持一级审核状态
    rentMin: null,
    rentMax: null
  })
  handleSearch()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getHouseList()
}

const handleViewDetails = (house: any) => {
  currentHouse.value = house
  showHouseDetailDrawer.value = true
}

const handleDrawerClose = () => {
  showHouseDetailDrawer.value = false
  currentHouse.value = null
}

// 审核操作
const handleApprove = async (house: any) => {
  try {
    await ElMessageBox.confirm(
      `确定通过房源"${house.title}"的一级审核吗？`,
      '审核确认',
      {
        confirmButtonText: '确定通过',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    const response = await baseService.put(`/rental/areaplothouse/${house.id}`, {
      ...house,
      state: 2 // 通过一级审核，进入二级审核
    })

    if (response.code === 0) {
      ElMessage.success('审核通过成功')
      getHouseList()
    } else {
      ElMessage.error(response.msg || '审核失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核失败:', error)
      ElMessage.error('审核失败')
    }
  }
}

const handleReject = async (house: any) => {
  try {
    await ElMessageBox.confirm(
      `确定拒绝房源"${house.title}"的一级审核吗？`,
      '审核确认',
      {
        confirmButtonText: '确定拒绝',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await baseService.put(`/rental/areaplothouse/${house.id}`, {
      ...house,
      state: 7 // 审核失败
    })

    if (response.code === 0) {
      ElMessage.success('审核拒绝成功')
      getHouseList()
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 初始化
onMounted(() => {
  getHouseList()
  getCountyList()
})
</script>

<style scoped>
/* 引用房源管理的样式 */
@import '@/styles/house-management.css';
</style>
